<template>
  <div class="daai-collapse">
    <slot></slot>
  </div>
</template>

<script setup>
import { provide, ref } from 'vue'
import { collapseProps, collapseContextKey } from './props'
defineOptions({
  name: 'DaaiCollapse',
})
const props = defineProps(collapseProps)

const emit = defineEmits(['change', 'update:modelValue'])

// 关于展开面板核心逻辑，其实就是判断数组里面的值
const activeNames = ref(props.modelValue)

const handleItemClick = (itemName) => {
  let _activeNames = activeNames.value.slice()

  if (props.accordion) {
    // 说明当前是手风琴模式
    _activeNames = [activeNames.value[0] === itemName ? '' : itemName]
  } else {
    // 普通面板
    // 获取当前数组的索引
    const index = _activeNames.indexOf(itemName)
    if (index > -1) {
      // 删除数组中的元素
      _activeNames.splice(index, 1)
    } else {
      _activeNames.push(itemName)
    }
  }

  activeNames.value = _activeNames

  emit('update:modelValue', _activeNames)
  emit('change', _activeNames)
}

provide(collapseContextKey, {
  activeNames,
  handleItemClick,
})
</script>

<style lang="scss" scoped></style>
